package com.bayihouse.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bayihouse.annotation.AuthCheck;
import com.bayihouse.common.BaseResponse;
import com.bayihouse.common.DeleteRequest;
import com.bayihouse.common.ErrorCode;
import com.bayihouse.common.ResultUtils;
import com.bayihouse.constant.AdministerConstant;
import com.bayihouse.exception.BusinessException;
import com.bayihouse.exception.ThrowUtils;
import com.bayihouse.model.entity.Administer;
import com.bayihouse.model.request.administer.*;
import com.bayihouse.model.vo.AdministerVO;
import com.bayihouse.model.vo.LoginAdministerVO;
import com.bayihouse.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.List;


@RestController
@RequestMapping("/administer")
@Slf4j
public class AdministerController {


    @Resource
    private AdministerService administerService;




    // region 登录相关

    /**
     * 用户注册
     *
     * @param administerRegisterRequest
     * @return
     */
    @PostMapping("/register")
    public BaseResponse<Long> administerRegister(@RequestBody AdministerRegisterRequest administerRegisterRequest) {

        if (administerRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String administerAccount = administerRegisterRequest.getUserAccount();
        String administerPassword = administerRegisterRequest.getUserPassword();
        String checkPassword = administerRegisterRequest.getUserPassword();
        if (StringUtils.isAnyBlank(administerAccount, administerPassword, checkPassword)) {
            return null;
        }
        long result = administerService.administerRegister(administerRegisterRequest);
        return ResultUtils.success(result);
    }

    /**
     * 用户登录
     *
     * @param administerLoginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<LoginAdministerVO> administerLogin(@RequestBody AdministerLoginRequest administerLoginRequest, HttpServletRequest request, HttpServletResponse response) throws ParseException, IOException {
        if (administerLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String administerAccount = administerLoginRequest.getUserAccount();
        String administerPassword = administerLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(administerAccount, administerPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        LoginAdministerVO loginAdministerVO = administerService.administerLogin(administerAccount, administerPassword, request);
        return ResultUtils.success(loginAdministerVO);
    }


    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Boolean> administerLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean result = administerService.administerLogout(request);
        return ResultUtils.success(result);
    }

    /**
     * 获取当前登录用户
     *
     * @param request
     * @return
     */
    @GetMapping("/get/login")
    public BaseResponse<LoginAdministerVO> getLoginAdminister(HttpServletRequest request) {
        System.out.println("hello-world" + request.getSession().getId());
        Administer administer = administerService.getLoginAdminister(request);
        return ResultUtils.success(administerService.getLoginAdministerVO(administer));
    }

    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param administerAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = AdministerConstant.ADMIN_ROLE)
    public BaseResponse<Long> addAdminister(@RequestBody AdministerAddRequest administerAddRequest, HttpServletRequest request) {
        if (administerAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Administer administer = new Administer();
        BeanUtils.copyProperties(administerAddRequest, administer);
        boolean result = administerService.save(administer);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(administer.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = AdministerConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteAdminister(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = administerService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param administerUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = AdministerConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateAdminister(@RequestBody AdministerUpdateRequest administerUpdateRequest,
                                                  HttpServletRequest request) {
        System.out.println(administerUpdateRequest);
        if (administerUpdateRequest == null || administerUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Administer administer = new Administer();
        BeanUtils.copyProperties(administerUpdateRequest, administer);
        boolean result = administerService.updateById(administer);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取用户（仅管理员）
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = AdministerConstant.ADMIN_ROLE)
    public BaseResponse<AdministerVO> getAdministerById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Administer administer = administerService.getById(id);
        ThrowUtils.throwIf(administer == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(administerService.getAdministerVO(administer));
    }

    public BaseResponse<Administer> getAdministerById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Administer administer = administerService.getById(id);
        ThrowUtils.throwIf(administer == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(administer);
    }

    /**
     * 根据 id 获取包装类
     *
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<AdministerVO> getAdministerVOById(long id, HttpServletRequest request) {
        BaseResponse<Administer> response = getAdministerById(id);
        Administer administer = response.getData();
        return ResultUtils.success(administerService.getAdministerVO(administer));
    }

    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param administerQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = AdministerConstant.ADMIN_ROLE)
    public BaseResponse<Page<Administer>> listAdministerByPage(@RequestBody AdministerQueryRequest administerQueryRequest,
                                                               HttpServletRequest request) {
        long current = administerQueryRequest.getCurrent();
        long size = administerQueryRequest.getPageSize();
        Page<Administer> administerPage = administerService.page(new Page<>(current, size),
                administerService.getQueryWrapper(administerQueryRequest));
        return ResultUtils.success(administerPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param administerQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = AdministerConstant.ADMIN_ROLE)
    public BaseResponse<Page<AdministerVO>> listAdministerVOByPage(@RequestBody AdministerQueryRequest administerQueryRequest,
                                                                   HttpServletRequest request) {
        if (administerQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = administerQueryRequest.getCurrent();
        long size = administerQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Administer> administerPage = administerService.page(new Page<>(current, size),
                administerService.getQueryWrapper(administerQueryRequest));
        System.out.println(administerPage.getRecords());
        Page<AdministerVO> administerVOPage = new Page<>(current, size, administerPage.getTotal());
        List<AdministerVO> administerVO = administerService.getAdministerVOList(administerPage.getRecords());
        administerVOPage.setRecords(administerVO);
        System.out.println(administerVOPage.getRecords());
        return ResultUtils.success(administerVOPage);
    }

    // endregion

    /**
     * 更新个人信息
     *
     * @param administerUpdateMyRequest
     * @param request
     * @return
     */
    @PostMapping("/update/my")
    public BaseResponse<Boolean> updateMyAdminister(@RequestBody AdministerUpdateMyRequest administerUpdateMyRequest,
                                                    HttpServletRequest request) {
        if (administerUpdateMyRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Administer loginAdminister = administerService.getLoginAdminister(request);
        Administer administer = new Administer();
        BeanUtils.copyProperties(administerUpdateMyRequest, administer);
        administer.setId(loginAdminister.getId());
        boolean result = administerService.updateById(administer);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
}
